package com.example.tbtx.tbtx;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.tbtx.tbtx.module.CheckVersionResponse;
import com.example.tbtx.tbtx.retrofit.RetrofitHelper;
import com.example.tbtx.tbtx.view.UpdateDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SpaceActivity extends Activity implements OnClickListener {
    private ImageView btn_spirit_world,btn_celestial_world,btn_god_world;
    public static int OVERLAY_PERMISSION_REQ_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_space);
        btn_spirit_world = (ImageView) findViewById(R.id.btn_spirit_world);
        btn_celestial_world = (ImageView) findViewById(R.id.btn_celestial_world);
        btn_god_world = (ImageView) findViewById(R.id.btn_god_world);
        findViewById(R.id.btn_test2_world).setOnClickListener(this);
        btn_spirit_world.setOnClickListener(this);
        btn_celestial_world.setOnClickListener(this);
        btn_god_world.setOnClickListener(this);
        findViewById(R.id.btn_test1_world).setOnClickListener(this);
        getPermission();
        checkUpData();
        Log.d("fsssssss", "onCreate: ");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("fsssssss", "onStart: ");
    }

    public void getPermission() {

        if (Build.VERSION.SDK_INT >= 23) {

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            }

            if (Settings.canDrawOverlays(this)) {

            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
            }
        }



    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT >= 23 && !Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "权限授予失败，无法开启悬浮窗", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "权限授予成功！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){

                }
        }
    }
    private void checkUpData() {
        RetrofitHelper.getApi().checkVersion().enqueue(new Callback<CheckVersionResponse>() {
            @Override
            public void onResponse(Call<CheckVersionResponse> call, Response<CheckVersionResponse> response) {
                try {
                    int versionCode = getPackageManager().getPackageInfo(SpaceActivity.this.getPackageName(), 0).versionCode;
                    if (response.body().getData().getApk_id() != versionCode) {
                        new UpdateDialog(SpaceActivity.this).show();
                        RetrofitHelper.getApi().downloadApk(response.body().getData().getApk_url()).enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                boolean success = saveData(response);
                                if (success) {
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                    Uri uriForFile = null;
                                    if (Build.VERSION.SDK_INT>=24){
                                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                        uriForFile= FileProvider.getUriForFile(SpaceActivity.this, BuildConfig.APPLICATION_ID + ".provider"
                                                , new File(Environment
                                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-release.apk"));
                                    }else {
                                        uriForFile=Uri.fromFile(new
                                                File(Environment
                                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-release.apk"));
                                    }

                                    intent.setDataAndType(
                                            uriForFile, "application/vnd.android.package-archive");
                                    startActivity(intent);

                                }

                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {

                            }
                        });
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(Call<CheckVersionResponse> call, Throwable t) {

            }
        });
    }

    private synchronized boolean saveData(Response<ResponseBody> response) {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-release.apk");

        long size = 0;
        byte[] bytes = new byte[40960];
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            long l = response.body().contentLength();
            inputStream = response.body().byteStream();
            fileOutputStream = new FileOutputStream(file);
            int read=0;
            while ((read = inputStream.read(bytes))!=-1) {
                fileOutputStream.write(bytes,0,read);
                size += read;
            }
//            fileOutputStream.flush();
            Log.d("fsssssss", "saveData: 下载完成");
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (fileOutputStream != null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // Method to start the service
    public void startService(View view) {

    }

    // Method to stop the service
    public void stopService(View view) {

    }


    @Override
    public void onClick(View view) {
        Intent intent=new Intent();

        switch(view.getId()){
            case R.id.btn_spirit_world:
            case R.id.btn_celestial_world:
            case R.id.btn_god_world:
            case R.id.btn_test2_world:
                Toast.makeText(this, "即将上线，敬请期待", Toast.LENGTH_SHORT).show();
                return;
            case R.id.btn_test1_world:
                intent.setClass(this,MainActivity.class);
                break;

        }
        startActivity(intent);
    }

}
